package cn.bailan.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.Map;

/**
 * Author:甲粒子
 * Date: 2021/11/16
 * Description：JWT工具包
 */
public class JWTUtil {
    private static final String KEY="20021016&*#423love34u!-ex)";
    /**
     * 生成token
     * 参数:  map
     * 返回: token (String)
     */
    public static String createToken(Map<String,String> map){
        JWTCreator.Builder builder= JWT.create();
        map.forEach((k,v)->{
            builder.withClaim(k,v);
        });
        Calendar instance=Calendar.getInstance();
        instance.add(Calendar.DAY_OF_WEEK,1);//一周后token过期
        builder.withExpiresAt(instance.getTime());
        return builder.sign(Algorithm.HMAC256(KEY)).toString();
    }

    /**
     * 验证token
     * 参数:  token
     * 返回: void
     */
    public static int verify(String token){
        try{
            JWT.require(Algorithm.HMAC256("KEY")).build().verify(token);//验证不成功就会抛出异常
            return 1;
        }catch (Exception e){
            return -1;
        }
    }

    /**
     * 获取token中的payload
     * 参数:  token
     * 返回: DecodeJWT
     */
    public static DecodedJWT getTokenPayload(String token){
        return JWT.require(Algorithm.HMAC256(KEY)).build().verify(token);
    }



    /**
     * 生成token
     * 参数:  map
     * 返回: token (String)
     */
    public static String doCreateToken(Map<String,String> map,Integer userId){
        map.put("userId",String.valueOf(userId));
        return  createToken(map);
    }
}
